package controller;

import static engine.BIEngine0_1.AlgorithmOperator.chmod;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;

import beans.HttpConfig;
import beans.LogEnum;
import dao.HistoryTaskDao;
import dao.TaskDao;
import net.TaskOperator;
import portal.cmd.JHCmd;
import portal.controller.BaseServlet;
import utils.FileOper;
import utils.Log4jInit;
import utils.StaticUtil;
import utils.UserLogUtil;

public class StartOrderServlet extends BaseServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private static final long MAX_FILE_SIZE = 1024 * 1024 * 20;
    private static final long MAX_REQUEST_SIZE = 1024 * 1024 * 30;
	@Autowired
	JHCmd jhCmd;
	@Autowired
	TaskOperator taskOperator ;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String modelId = request.getParameter("modelId");
        String priority = request.getParameter("priority");
        //调度策略
        String parallelStrategy = request.getParameter("parallelStrategy");
        String userId = (String) request.getSession().getAttribute("userId");

        String poffix = request.getParameter("suffix");
        String files = request.getParameter("files");
        String others= request.getParameter("others");
        
        List<String> modelXmlDirList = new ArrayList<>();

        //启动任务
        JSONObject result = new JSONObject();
        Log4jInit.logger.info("----others:----"+others);
        // TODO: 2018/8/16 需要考虑
        String taskHash = UUID.randomUUID().toString().substring(0,20);;
        if(checkModelAndSaveInfo(modelId)){
        		result.put("message", "任务发起失败，可能存在一个正在运行的空三任务，或出现其他错误！");
            result.put("result", false);
            response.getWriter().write(result.toString());
        	return;
        }
        
        // TODO: 2018/8/16 最后需要删除
    //    userId = "-1";

        // 接收文件
        File storeFile = null;
        String filePath = "";
        
     // base64转byte[]
        if(files!=null){
        	
     		byte[] decodeBase64 = Base64.decodeBase64(files);
     		// byte[]转inputstream
     		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decodeBase64);

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        String rootFilePath = HttpConfig.tempOutput;
//        String ftpParamsUri = HttpConfig.ftpParamsUri;
        
        File rootFileDir = new File(rootFilePath);
        if (!rootFileDir.exists()) {
            rootFileDir.mkdir();
            chmod(rootFilePath);
        }

        String folderName = UUID.randomUUID().toString().substring(0,20);
        String uploadPath = rootFilePath + folderName;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        
     // inputstream写到文件
        filePath = uploadPath+"/"+poffix;
        //filePath = uploadPath+"/"+poffix.substring(0,(poffix.lastIndexOf(".")));
        File dirs = new File(uploadPath+"/"+poffix.substring(0,(poffix.lastIndexOf("."))));
        if (!dirs.exists()) {
            dirs.mkdir();
        }
        Log4jInit.logger.info("----filePath----------"+filePath);
       // UserLogUtil.log("--------------"+filePath);	
        FileUtils.copyInputStreamToFile(byteArrayInputStream, new File(filePath));
    
    
        
 		if(poffix.substring((poffix.lastIndexOf(".")+1)).equals("zip")){
 			modelXmlDirList = StaticUtil.unzipWithoutOuterFolder(filePath, uploadPath);
            //删除zip文件
            StaticUtil.deleteFile(filePath);
 			
 		}else{
 			modelXmlDirList.add(filePath);
 		}
    }      


        if (modelId != null) {
            result = taskOperator.startModel(modelId, taskHash, priority,
                    parallelStrategy, modelXmlDirList, userId,others);
            response.getWriter().write(result.toString());
            // 日志记录
            UserLogUtil.dbLog(LogEnum.historyTask, LogEnum.startHistoryTask,
                    userId, LogEnum.task.getValue()+"编号："+modelId+"，"+LogEnum.historyTask.getValue()+"哈希值："+taskHash);
//            JSONObject other=null;
//            if(others!=null && others.length()>2){
//            	other= JSONObject.fromObject(others);
//            	jhCmd.hostOpen(other.getString("node"));
//            	}
        } else {
            result.put("message", "接收到的任务标识为空");
            result.put("result", false);
            response.getWriter().write(result.toString());
        }


    }
    /*****
     * @return fasle:to continue,true means is exclusive model but  may start one before or can not save start flag;
     * 
     * ****/
    private boolean checkModelAndSaveInfo(String modelId){
    	//if model is not exclusive model ,return fasle;
    	if(false==isExclusiveModelIdAndJust(modelId))
    		return false;
    	if(saveExclusiveToFile(modelId))
    		return false;
    	return true;
    }
    public static  boolean isExclusiveModelIdAndJust(String modelId){
    	if(modelId==null ||HttpConfig.modelIds==null || HttpConfig.modelIds.length()<=2)
    	return false;
    	if(HttpConfig.modelIds.contains("#"+modelId+"#"))
    		return true;
    	return false;
    }
    public synchronized boolean saveExclusiveToFile(String modelId){
    	if(modelId==null||modelId.length()==0)
    		return false;
    	String filePath =HttpConfig.taskJsonFileUri+""+modelId+"_exclusiveNode.json";
    	File f=new File(filePath);
    	if(f.exists())///表示文件已存在，不能保存当前请求信息
    		return false;
    	try {
			if(f.createNewFile()==false){
				return false;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log4jInit.logger.error("IO Exception : create file Failed "+ filePath);
			return false;
		}
    	return true;
    }
}
